<template>
  <div class="map-container">
    <div class="control-panel">
      <h3>地图控制</h3>
      <div class="control-group">
        <button @click="toggleMapType" class="btn">
          {{ mapType === '2D' ? '切换到3D' : '切换到2D' }}
        </button>
        <button @click="getCurrentLocation" class="btn">
          定位当前位置
        </button>
        <button @click="addRandomMarker" class="btn">
          添加随机标记
        </button>
        <button @click="clearMarkers" class="btn">
          清除标记
        </button>
      </div>
      
      <div class="info-panel">
        <div class="info-item">
          <span class="label">经度:</span>
          <span class="value">{{ currentLng }}</span>
        </div>
        <div class="info-item">
          <span class="label">纬度:</span>
        <span class="value">{{ currentLat }}</span>
        </div>
        <div class="info-item">
          <span class="label">地址:</span>
          <span class="value">{{ currentAddress }}</span>
        </div>
      </div>
    </div>
    
    <div class="search-box">
      <input 
        v-model="searchKeyword" 
        @keyup.enter="searchLocation"
        placeholder="输入地址进行搜索..."
        class="search-input"
      />
      <button @click="searchLocation" class="search-btn">
          搜索
        </button>
      </div>
    
    <div id="map" ref="mapContainer" class="map"></div>
    
    <div v-if="loading" class="loading">
      <div class="spinner"></div>
      <span>地图加载中...</span>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import AMapLoader from '@amap/amap-jsapi-loader'

// 响应式数据
const mapContainer = ref(null)
const map = ref(null)
const loading = ref(true)
const mapType = ref('2D')
const currentLng = ref('')
const currentLat = ref('')
const currentAddress = ref('')
const searchKeyword = ref('')
const markers = ref([])

// 配置安全密钥（请替换为您的实际密钥）
window._AMapSecurityConfig = {
  securityJsCode: '你的高德secret'
}

// 初始化地图
const initMap = async () => {
  try {
    loading.value = true
    
    const AMap = await AMapLoader.load({
      key: '你的高德key', // 请替换为您的实际Key
      version: '2.0',
      plugins: ['AMap.Geolocation', 'AMap.Geocoder', 'AMap.PlaceSearch', 'AMap.ToolBar']
    })

    // 创建地图实例
    map.value = new AMap.Map(mapContainer.value, {
      zoom: 13,
      center: [116.397428, 39.90923], // 北京天安门
      viewMode: mapType.value,
      mapStyle: 'amap://styles/light'
    })

    // 添加工具栏
    map.value.addControl(new AMap.ToolBar())

    // 绑定地图点击事件
    map.value.on('click', handleMapClick)

    loading.value = false
    console.log('高德地图初始化成功')
  } catch (error) {
    console.error('地图初始化失败:', error)
    loading.value = false
  }
}

// 地图点击事件处理
const handleMapClick = (e) => {
  currentLng.value = e.lnglat.getLng().toFixed(6)
  currentLat.value = e.lnglat.getLat().toFixed(6)
  reverseGeocode(e.lnglat)
}

// 逆地理编码
const reverseGeocode = (lnglat) => {
  const geocoder = new AMap.Geocoder()
  geocoder.getAddress(lnglat, (status, result) => {
    if (status === 'complete' && result.info === 'OK') {
      currentAddress.value = result.regeocode.formattedAddress
    }
  })
}

// 切换地图类型
const toggleMapType = () => {
  mapType.value = mapType.value === '2D' ? '3D' : '2D'
  if (map.value) {
    map.value.setViewMode(mapType.value)
  }
}

// 获取当前位置
const getCurrentLocation = () => {
  if (!map.value) return
  
  const geolocation = new AMap.Geolocation({
    enableHighAccuracy: true,
    timeout: 10000,
    buttonOffset: new AMap.Pixel(10, 20),
    zoomToAccuracy: true
  })

  geolocation.getCurrentPosition((status, result) => {
    if (status === 'complete') {
      currentLng.value = result.position.getLng().toFixed(6)
      currentLat.value = result.position.getLat().toFixed(6)
      map.value.setCenter([result.position.getLng(), result.position.getLat()])
      addMarker(result.position, '当前位置')
      reverseGeocode(result.position)
    } else {
      console.error('定位失败:', result)
      alert('定位失败，请检查浏览器定位权限')
    }
  })
}

// 添加标记
const addMarker = (position, title = '标记点') => {
  if (!map.value) return
  
  const marker = new AMap.Marker({
    position: position,
    title: title,
    offset: new AMap.Pixel(-13, -30)
  })

  map.value.add(marker)
  markers.value.push(marker)
  
  // 自动调整视野以显示所有标记
  map.value.setFitView()
}

// 添加随机标记
const addRandomMarker = () => {
  if (!map.value) return
  
  const center = map.value.getCenter()
  const lng = center.getLng() + (Math.random() - 0.5) * 0.1
  const lat = center.getLat() + (Math.random() - 0.5) * 0.1
  
  addMarker([lng, lat], `随机标记${markers.value.length + 1}`)
}

// 清除所有标记
const clearMarkers = () => {
  if (!map.value) return
  
  markers.value.forEach(marker => {
    map.value.remove(marker)
  })
  markers.value = []
}

// 搜索位置
const searchLocation = () => {
  if (!searchKeyword.value.trim() || !map.value) return
  
  const placeSearch = new AMap.PlaceSearch({
    city: '全国',
    pageSize: 5
  })

  placeSearch.search(searchKeyword.value, (status, result) => {
    if (status === 'complete' && result.info === 'OK') {
      const pois = result.poiList.pois
      if (pois.length > 0) {
        const firstPoi = pois[0]
        map.value.setCenter([firstPoi.location.getLng(), firstPoi.location.getLat()])
        addMarker(firstPoi.location, firstPoi.name)
        currentAddress.value = firstPoi.address
      }
    }
  })
}

// 组件挂载时初始化地图
onMounted(() => {
  initMap()
})

// 组件卸载时清理资源
onUnmounted(() => {
  if (map.value) {
    map.value.destroy()
  }
})
</script>

<style scoped>
.map-container {
  position: relative;
  width: 100%;
  height: 450px;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
}

.map {
  width: 100%;
  height: 100%;
}

.control-panel {
  position: absolute;
  top: 20px;
  left: 20px;
  z-index: 100;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  padding: 1rem;
  border-radius: 8px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
  min-width: 250px;
}

.control-panel h3 {
  margin-bottom: 1rem;
  color: #333;
  font-size: 1.1rem;
}

.control-group {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

.btn {
  padding: 0.5rem 1rem;
  background: linear-gradient(135deg, #667eea, #764ba2);
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: 0.9rem;
}

.btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
}

.info-panel {
  margin-top: 1rem;
  padding-top: 1rem;
  border-top: 1px solid rgba(0, 0, 0, 0.1);
}

.info-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 0.5rem;
  font-size: 0.85rem;
}

.label {
  color: #666;
  font-weight: 500;
}

.value {
  color: #333;
  font-weight: 600;
}

.search-box {
  position: absolute;
  top: 20px;
  right: 20px;
  z-index: 100;
  display: flex;
  gap: 0.5rem;
}

.search-input {
  padding: 0.5rem 1rem;
  border: 1px solid #ddd;
  border-radius: 6px;
  width: 250px;
  font-size: 0.9rem;
}

.search-input:focus {
  outline: none;
  border-color: #667eea;
}

.search-btn {
  padding: 0.5rem 1rem;
  background: #667eea;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.search-btn:hover {
  background: #5a6fd8;
  transform: translateY(-1px);
}

.loading {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 101;
  background: rgba(255, 255, 255, 0.9);
  padding: 1rem 2rem;
  border-radius: 8px;
  display: flex;
  align-items: center;
  gap: 1rem;
  color: #333;
}

.spinner {
  width: 20px;
  height: 20px;
  border: 2px solid #f3f3f3;
  border-top: 2px solid #667eea;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}
</style>